home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 2 / AACD 2.iso / AACD / Programming / perlman / man / perldata.txt < prev    next >
Encoding:
Text File  |  1999-09-09  |  23.8 KB  |  578 lines

  1. NAME
  2.        perldata - Perl data types
  3.  
  4. DESCRIPTION
  5.        Variable names
  6.  
  7.        Perl has three data structures: scalars, arrays of
  8.        scalars, and associative arrays of scalars, known as
  9.        "hashes".  Normal arrays are indexed by number, starting
  10.        with 0.  (Negative subscripts count from the end.)  Hash
  11.        arrays are indexed by string.
  12.  
  13.        Scalar values are always named with '$', even when
  14.        referring to a scalar that is part of an array.  It works
  15.        like the English word "the".  Thus we have:
  16.  
  17.            $days               # the simple scalar value "days"
  18.            $days[28]           # the 29th element of array @days
  19.            $days{'Feb'}        # the 'Feb' value from hash %days
  20.            $#days              # the last index of array @days
  21.  
  22.        but entire arrays or array slices are denoted by '@',
  23.        which works much like the word "these" or "those":
  24.  
  25.            @days               # ($days[0], $days[1],... $days[n])
  26.            @days[3,4,5]        # same as @days[3..5]
  27.            @days{'a','c'}      # same as ($days{'a'},$days{'c'})
  28.  
  29.        and entire hashes are denoted by '%':
  30.  
  31.            %days               # (key1, val1, key2, val2 ...)
  32.  
  33.        In addition, subroutines are named with an initial '&',
  34.        though this is optional when it's otherwise unambiguous
  35.        (just as "do" is often redundant in English).  Symbol
  36.        table entries can be named with an initial '*', but you
  37.        don't really care about that yet.
  38.  
  39.        Every variable type has its own namespace.  You can,
  40.        without fear of conflict, use the same name for a scalar
  41.        variable, an array, or a hash (or, for that matter, a
  42.        filehandle, a subroutine name, or a label).  This means
  43.        that $foo and @foo are two different variables.  It also
  44.        means that $foo[1] is a part of @foo, not a part of $foo.
  45.        This may seem a bit weird, but that's okay, because it is
  46.        weird.
  47.  
  48.        Since variable and array references always start with '$',
  49.        '@', or '%', the "reserved" words aren't in fact reserved
  50.        with respect to variable names.  (They ARE reserved with
  51.        respect to labels and filehandles, however, which don't
  52.        have an initial special character.  You can't have a
  53.        filehandle named "log", for instance.  Hint: you could say
  54.        open(LOG,'logfile') rather than open(log,'logfile').
  55.        Using uppercase filehandles also improves readability and
  56.        protects you from conflict with future reserved words.)
  57.        Case IS significant--"FOO", "Foo" and "foo" are all
  58.        different names.  Names that start with a letter or
  59.        underscore may also contain digits and underscores.
  60.  
  61.        It is possible to replace such an alphanumeric name with
  62.        an expression that returns a reference to an object of
  63.        that type.  For a description of this, see the perlref
  64.        manpage.
  65.  
  66.        Names that start with a digit may only contain more
  67.        digits.  Names which do not start with a letter,
  68.        underscore,  or digit are limited to one character, e.g.
  69.        $% or $$.  (Most of these one character names have a
  70.        predefined significance to Perl.  For instance, $$ is the
  71.        current process id.)
  72.  
  73.        Context
  74.  
  75.        The interpretation of operations and values in Perl
  76.        sometimes depends on the requirements of the context
  77.        around the operation or value.  There are two major
  78.        contexts: scalar and list.  Certain operations return list
  79.        values in contexts wanting a list, and scalar values
  80.        otherwise.  (If this is true of an operation it will be
  81.        mentioned in the documentation for that operation.)  In
  82.        other words, Perl overloads certain operations based on
  83.        whether the expected return value is singular or plural.
  84.        (Some words in English work this way, like "fish" and
  85.        "sheep".)
  86.  
  87.        In a reciprocal fashion, an operation provides either a
  88.        scalar or a list context to each of its arguments.  For
  89.        example, if you say
  90.  
  91.            int( <STDIN> )
  92.  
  93.        the integer operation provides a scalar context for the
  94.        <STDIN> operator, which responds by reading one line from
  95.        STDIN and passing it back to the integer operation, which
  96.        will then find the integer value of that line and return
  97.        that.  If, on the other hand, you say
  98.  
  99.            sort( <STDIN> )
  100.  
  101.        then the sort operation provides a list context for
  102.        <STDIN>, which will proceed to read every line available
  103.        up to the end of file, and pass that list of lines back to
  104.        the sort routine, which will then sort those lines and
  105.        return them as a list to whatever the context of the sort
  106.        was.
  107.  
  108.        Assignment is a little bit special in that it uses its
  109.        left argument to determine the context for the right
  110.        argument.  Assignment to a scalar evaluates the righthand
  111.        side in a scalar context, while assignment to an array or
  112.        array slice evaluates the righthand side in a list
  113.        context.  Assignment to a list also evaluates the
  114.        righthand side in a list context.
  115.  
  116.        User defined subroutines may choose to care whether they
  117.        are being called in a scalar or list context, but most
  118.        subroutines do not need to care, because scalars are
  119.        automatically interpolated into lists.  See the wantarray
  120.        entry in the perlfunc manpage.
  121.  
  122.        Scalar values
  123.  
  124.        All data in Perl is a scalar or an array of scalars or a
  125.        hash of scalars.  Scalar variables may contain various
  126.        kinds of singular data, such as numbers, strings, and
  127.        references.  In general, conversion from one form to
  128.        another is transparent.  (A scalar may not contain
  129.        multiple values, but may contain a reference to an array
  130.        or hash containing multiple values.)  Because of the
  131.        automatic conversion of scalars, operations and functions
  132.        that return scalars don't need to care (and, in fact,
  133.        can't care) whether the context is looking for a string or
  134.        a number.
  135.  
  136.        Scalars aren't necessarily one thing or another.  There's
  137.        no place to declare a scalar variable to be of type
  138.        "string", or of type "number", or type "filehandle", or
  139.        anything else.  Perl is a contextually polymorphic
  140.        language whose scalars can be strings, numbers, or
  141.        references (which includes objects).  While strings and
  142.        numbers are considered pretty much same thing for nearly
  143.        all purposes, references are strongly-typed uncastable
  144.        pointers with built-in reference-counting and destructor
  145.        invocation.
  146.  
  147.        A scalar value is interpreted as TRUE in the Boolean sense
  148.        if it is not the null string or the number 0 (or its
  149.        string equivalent, "0").  The Boolean context is just a
  150.        special kind of scalar context.
  151.  
  152.        There are actually two varieties of null scalars: defined
  153.        and undefined.  Undefined null scalars are returned when
  154.        there is no real value for something, such as when there
  155.        was an error, or at end of file, or when you refer to an
  156.        uninitialized variable or element of an array.  An
  157.        undefined null scalar may become defined the first time
  158.        you use it as if it were defined, but prior to that you
  159.        can use the defined() operator to determine whether the
  160.        value is defined or not.
  161.  
  162.        To find out whether a given string is a valid non-zero
  163.        number, it's usually enough to test it against both
  164.        numeric 0 and also lexical "0" (although this will cause
  165.        -w noises).  That's because strings that aren't numbers
  166.        count as 0, just as the do in awk:
  167.  
  168.            if ($str == 0 && $str ne "0")  {
  169.                warn "That doesn't look like a number";
  170.            }
  171.  
  172.        That's usually preferable because otherwise you won't
  173.        treat IEEE notations like NaN or Infinity properly.  At
  174.        other times you might prefer to use a regular expression
  175.        to check whether data is numeric.  See the perlre manpage
  176.        for details on regular expressions.
  177.  
  178.            warn "has nondigits"        if     /\D/;
  179.            warn "not a whole number"   unless /^\d+$/;
  180.            warn "not an integer"       unless /^[+-]?\d+$/
  181.            warn "not a decimal number" unless /^[+-]?\d+\.?\d*$/
  182.            warn "not a C float"
  183.                unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;
  184.  
  185.        The length of an array is a scalar value.  You may find
  186.        the length of array @days by evaluating $#days, as in csh.
  187.        (Actually, it's not the length of the array, it's the
  188.        subscript of the last element, since there is (ordinarily)
  189.        a 0th element.)  Assigning to $#days changes the length of
  190.        the array.  Shortening an array by this method destroys
  191.        intervening values.  Lengthening an array that was
  192.        previously shortened NO LONGER recovers the values that
  193.        were in those elements.  (It used to in Perl 4, but we had
  194.        to break this make to make sure destructors were called
  195.        when expected.)  You can also gain some measure of
  196.        efficiency by preextending an array that is going to get
  197.        big.  (You can also extend an array by assigning to an
  198.        element that is off the end of the array.)  You can
  199.        truncate an array down to nothing by assigning the null
  200.        list () to it.  The following are equivalent:
  201.  
  202.            @whatever = ();
  203.            $#whatever = $[ - 1;
  204.  
  205.        If you evaluate a named array in a scalar context, it
  206.        returns the length of the array.  (Note that this is not
  207.        true of lists, which return the last value, like the C
  208.        comma operator.)  The following is always true:
  209.  
  210.            scalar(@whatever) == $#whatever - $[ + 1;
  211.  
  212.        Version 5 of Perl changed the semantics of $[: files that
  213.        don't set the value of $[ no longer need to worry about
  214.        whether another file changed its value.  (In other words,
  215.        use of $[ is deprecated.)  So in general you can just
  216.        assume that
  217.            scalar(@whatever) == $#whatever + 1;
  218.  
  219.        Some programmers choose to use an explicit conversion so
  220.        nothing's left to doubt:
  221.  
  222.            $element_count = scalar(@whatever);
  223.  
  224.        If you evaluate a hash in a scalar context, it returns a
  225.        value which is true if and only if the hash contains any
  226.        key/value pairs.  (If there are any key/value pairs, the
  227.        value returned is a string consisting of the number of
  228.        used buckets and the number of allocated buckets,
  229.        separated by a slash.  This is pretty much only useful to
  230.        find out whether Perl's (compiled in) hashing algorithm is
  231.        performing poorly on your data set.  For example, you
  232.        stick 10,000 things in a hash, but evaluating %HASH in
  233.        scalar context reveals "1/16", which means only one out of
  234.        sixteen buckets has been touched, and presumably contains
  235.        all 10,000 of your items.  This isn't supposed to happen.)
  236.  
  237.        Scalar value constructors
  238.  
  239.        Numeric literals are specified in any of the customary
  240.        floating point or integer formats:
  241.  
  242.            12345
  243.            12345.67
  244.            .23E-10
  245.            0xffff              # hex
  246.            0377                # octal
  247.            4_294_967_296       # underline for legibility
  248.  
  249.        String literals are usually delimited by either single or
  250.        double quotes.  They work much like shell quotes:  double-
  251.        quoted string literals are subject to backslash and
  252.        variable substitution; single-quoted strings are not
  253.        (except for "\'" and "\\").  The usual Unix backslash
  254.        rules apply for making characters such as newline, tab,
  255.        etc., as well as some more exotic forms.  See the qq entry
  256.        in the perlop manpage for a list.
  257.  
  258.        You can also embed newlines directly in your strings, i.e.
  259.        they can end on a different line than they begin.  This is
  260.        nice, but if you forget your trailing quote, the error
  261.        will not be reported until Perl finds another line
  262.        containing the quote character, which may be much further
  263.        on in the script.  Variable substitution inside strings is
  264.        limited to scalar variables, arrays, and array slices.
  265.        (In other words, identifiers beginning with $ or @,
  266.        followed by an optional bracketed expression as a
  267.        subscript.)  The following code segment prints out "The
  268.        price is $100."
  269.  
  270.            $Price = '$100';    # not interpreted
  271.            print "The price is $Price.\n";     # interpreted
  272.  
  273.        As in some shells, you can put curly brackets around the
  274.        identifier to delimit it from following alphanumerics.  In
  275.        fact, an identifier within such curlies is forced to be a
  276.        string, as is any single identifier within a hash
  277.        subscript.  Our earlier example,
  278.  
  279.            $days{'Feb'}
  280.  
  281.        can be written as
  282.  
  283.            $days{Feb}
  284.  
  285.        and the quotes will be assumed automatically.  But
  286.        anything more complicated in the subscript will be
  287.        interpreted as an expression.
  288.  
  289.        Note that a single-quoted string must be separated from a
  290.        preceding word by a space, since single quote is a valid
  291.        (though deprecated) character in an identifier (see the
  292.        Packages entry in the perlmod manpage).
  293.  
  294.        Two special literals are __LINE__ and __FILE__, which
  295.        represent the current line number and filename at that
  296.        point in your program.  They may only be used as separate
  297.        tokens; they will not be interpolated into strings.  In
  298.        addition, the token __END__ may be used to indicate the
  299.        logical end of the script before the actual end of file.
  300.        Any following text is ignored, but may be read via the
  301.        DATA filehandle.  (The DATA filehandle may read data only
  302.        from the main script, but not from any required file or
  303.        evaluated string.)  The two control characters ^D and ^Z
  304.        are synonyms for __END__ (or __DATA__ in a module; see the
  305.        SelfLoader manpage for details on __DATA__).
  306.  
  307.        A word that has no other interpretation in the grammar
  308.        will be treated as if it were a quoted string.  These are
  309.        known as "barewords".  As with filehandles and labels, a
  310.        bareword that consists entirely of lowercase letters risks
  311.        conflict with future reserved words, and if you use the -w
  312.        switch, Perl will warn you about any such words.  Some
  313.        people may wish to outlaw barewords entirely.  If you say
  314.  
  315.            use strict 'subs';
  316.  
  317.        then any bareword that would NOT be interpreted as a
  318.        subroutine call produces a compile-time error instead.
  319.        The restriction lasts to the end of the enclosing block.
  320.        An inner block may countermand this by saying no strict
  321.        'subs'.
  322.  
  323.        Array variables are interpolated into double-quoted
  324.        strings by joining all the elements of the array with the
  325.        delimiter specified in the $" variable ($LIST_SEPARATOR in
  326.        English), space by default.  The following are equivalent:
  327.  
  328.            $temp = join($",@ARGV);
  329.            system "echo $temp";
  330.  
  331.            system "echo @ARGV";
  332.  
  333.        Within search patterns (which also undergo double-quotish
  334.        substitution) there is a bad ambiguity:  Is /$foo[bar]/ to
  335.        be interpreted as /${foo}[bar]/ (where [bar] is a
  336.        character class for the regular expression) or as
  337.        /${foo[bar]}/ (where [bar] is the subscript to array
  338.        @foo)?  If @foo doesn't otherwise exist, then it's
  339.        obviously a character class.  If @foo exists, Perl takes a
  340.        good guess about [bar], and is almost always right.  If it
  341.        does guess wrong, or if you're just plain paranoid, you
  342.        can force the correct interpretation with curly brackets
  343.        as above.
  344.  
  345.        A line-oriented form of quoting is based on the shell
  346.        "here-doc" syntax.  Following a << you specify a string to
  347.        terminate the quoted material, and all lines following the
  348.        current line down to the terminating string are the value
  349.        of the item.  The terminating string may be either an
  350.        identifier (a word), or some quoted text.  If quoted, the
  351.        type of quotes you use determines the treatment of the
  352.        text, just as in regular quoting.  An unquoted identifier
  353.        works like double quotes.  There must be no space between
  354.        the << and the identifier.  (If you put a space it will be
  355.        treated as a null identifier, which is valid, and matches
  356.        the first blank line.)  The terminating string must appear
  357.        by itself (unquoted and with no surrounding whitespace) on
  358.        the terminating line.
  359.  
  360.                print <<EOF;
  361.            The price is $Price.
  362.            EOF
  363.  
  364.                print <<"EOF";  # same as above
  365.            The price is $Price.
  366.            EOF
  367.  
  368.                print <<`EOC`;  # execute commands
  369.            echo hi there
  370.            echo lo there
  371.            EOC
  372.  
  373.                print <<"foo", <<"bar"; # you can stack them
  374.            I said foo.
  375.            foo
  376.            I said bar.
  377.            bar
  378.                myfunc(<<"THIS", 23, <<'THAT');
  379.            Here's a line
  380.            or two.
  381.            THIS
  382.            and here another.
  383.            THAT
  384.  
  385.        Just don't forget that you have to put a semicolon on the
  386.        end to finish the statement, as Perl doesn't know you're
  387.        not going to try to do this:
  388.  
  389.                print <<ABC
  390.            179231
  391.            ABC
  392.                + 20;
  393.  
  394.        List value constructors
  395.  
  396.        List values are denoted by separating individual values by
  397.        commas (and enclosing the list in parentheses where
  398.        precedence requires it):
  399.  
  400.            (LIST)
  401.  
  402.        In a context not requiring a list value, the value of the
  403.        list literal is the value of the final element, as with
  404.        the C comma operator.  For example,
  405.  
  406.            @foo = ('cc', '-E', $bar);
  407.  
  408.        assigns the entire list value to array foo, but
  409.  
  410.            $foo = ('cc', '-E', $bar);
  411.  
  412.        assigns the value of variable bar to variable foo.  Note
  413.        that the value of an actual array in a scalar context is
  414.        the length of the array; the following assigns to $foo the
  415.        value 3:
  416.  
  417.            @foo = ('cc', '-E', $bar);
  418.            $foo = @foo;                # $foo gets 3
  419.  
  420.        You may have an optional comma before the closing
  421.        parenthesis of an list literal, so that you can say:
  422.  
  423.            @foo = (
  424.                1,
  425.                2,
  426.                3,
  427.            );
  428.  
  429.        LISTs do automatic interpolation of sublists.  That is,
  430.        when a LIST is evaluated, each element of the list is
  431.        evaluated in a list context, and the resulting list value
  432.        is interpolated into LIST just as if each individual
  433.        element were a member of LIST.  Thus arrays lose their
  434.        identity in a LIST--the list
  435.  
  436.            (@foo,@bar,&SomeSub)
  437.  
  438.        contains all the elements of @foo followed by all the
  439.        elements of @bar, followed by all the elements returned by
  440.        the subroutine named SomeSub when it's called in a list
  441.        context.  To make a list reference that does NOT
  442.        interpolate, see the perlref manpage.
  443.  
  444.        The null list is represented by ().  Interpolating it in a
  445.        list has no effect.  Thus ((),(),()) is equivalent to ().
  446.        Similarly, interpolating an array with no elements is the
  447.        same as if no array had been interpolated at that point.
  448.  
  449.        A list value may also be subscripted like a normal array.
  450.        You must put the list in parentheses to avoid ambiguity.
  451.        Examples:
  452.  
  453.            # Stat returns list value.
  454.            $time = (stat($file))[8];
  455.  
  456.            # SYNTAX ERROR HERE.
  457.            $time = stat($file)[8];  # OOPS, FORGOT PARENS
  458.  
  459.            # Find a hex digit.
  460.            $hexdigit = ('a','b','c','d','e','f')[$digit-10];
  461.  
  462.            # A "reverse comma operator".
  463.            return (pop(@foo),pop(@foo))[0];
  464.  
  465.        Lists may be assigned to if and only if each element of
  466.        the list is legal to assign to:
  467.  
  468.            ($a, $b, $c) = (1, 2, 3);
  469.  
  470.            ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);
  471.  
  472.        Array assignment in a scalar context returns the number of
  473.        elements produced by the expression on the right side of
  474.        the assignment:
  475.  
  476.            $x = (($foo,$bar) = (3,2,1));       # set $x to 3, not 2
  477.            $x = (($foo,$bar) = f());           # set $x to f()'s return count
  478.  
  479.        This is very handy when you want to do a list assignment
  480.        in a Boolean context, since most list functions return a
  481.        null list when finished, which when assigned produces a 0,
  482.        which is interpreted as FALSE.
  483.  
  484.        The final element may be an array or a hash:
  485.            ($a, $b, @rest) = split;
  486.            local($a, $b, %rest) = @_;
  487.  
  488.        You can actually put an array or hash anywhere in the
  489.        list, but the first one in the list will soak up all the
  490.        values, and anything after it will get a null value.  This
  491.        may be useful in a local() or my().
  492.  
  493.        A hash literal contains pairs of values to be interpreted
  494.        as a key and a value:
  495.  
  496.            # same as map assignment above
  497.            %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
  498.  
  499.        While literal lists and named arrays are usually
  500.        interchangeable, that's not the case for hashes.  Just
  501.        because you can subscript a list value like a normal array
  502.        does not mean that you can subscript a list value as a
  503.        hash.  Likewise, hashes included as parts of other lists
  504.        (including parameters lists and return lists from
  505.        functions) always flatten out into key/value pairs.
  506.        That's why it's good to use references sometimes.
  507.  
  508.        It is often more readable to use the => operator between
  509.        key/value pairs.  The => operator is mostly just a more
  510.        visually distinctive synonym for a comma, but it also
  511.        quotes its left-hand operand, which makes it nice for
  512.        initializing hashes:
  513.  
  514.            %map = (
  515.                         red   => 0x00f,
  516.                         blue  => 0x0f0,
  517.                         green => 0xf00,
  518.           );
  519.  
  520.        or for initializing hash references to be used as records:
  521.  
  522.            $rec = {
  523.                        witch => 'Mable the Merciless',
  524.                        cat   => 'Fluffy the Ferocious',
  525.                        date  => '10/31/1776',
  526.            };
  527.  
  528.        or for using call-by-named-parameter to complicated
  529.        functions:
  530.  
  531.           $field = $query->radio_group(
  532.                       name      => 'group_name',
  533.                       values    => ['eenie','meenie','minie'],
  534.                       default   => 'meenie',
  535.                       linebreak => 'true',
  536.                       labels    => \%labels
  537.           );
  538.  
  539.        Note that just because a hash is initialized in that order
  540.        doesn't mean that it comes out in that order.  See the
  541.        sort entry in the perlfunc manpage for examples of how to
  542.        arrange for an output ordering.
  543.  
  544.        Typeglobs and FileHandles
  545.  
  546.        Perl uses an internal type called a typeglob to hold an
  547.        entire symbol table entry.  The type prefix of a typeglob
  548.        is a *, because it represents all types.  This used to be
  549.        the preferred way to pass arrays and hashes by reference
  550.        into a function, but now that we have real references,
  551.        this is seldom needed.
  552.  
  553.        One place where you still use typeglobs (or references
  554.        thereto) is for passing or storing filehandles.  If you
  555.        want to save away a filehandle, do it this way:
  556.  
  557.            $fh = *STDOUT;
  558.  
  559.        or perhaps as a real reference, like this:
  560.  
  561.            $fh = \*STDOUT;
  562.  
  563.        This is also the way to create a local filehandle.  For
  564.        example:
  565.  
  566.            sub newopen {
  567.                my $path = shift;
  568.                local *FH;  # not my!
  569.                open (FH, $path) || return undef;
  570.                return \*FH;
  571.            }
  572.            $fh = newopen('/etc/passwd');
  573.  
  574.        See the perlref manpage, the perlsub manpage, and the
  575.        section on Symbols Tables in the perlmod manpage for more
  576.        discussion on typeglobs.  See the open entry in the
  577.        perlfunc manpage for other ways of generating filehandles.
  578.